package com.fingard.dsp.bank.directbank.gxnx02;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/10/10.
 */
public class GXNX02Transaction extends GXNX02Base implements ITransaction {

    /**
     * 历史明细查询
     *
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        return d_7516_HisTransB(p_req7516);
    }

    public RetAtsTrans d_7516_HisTransB(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAtsTrans.writeStart();
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            String pagesize = getBankConfig().getValueAsString("pageSize");
            if (StringHelper.isNullOrEmpty(pagesize)) {
                pagesize = "8";
            }
            while (tmpIntDateFrom <= tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                int tmpNowReadStart = 1;
                int tmpNowReadNum = 0;
                Map<String, Integer> tmpTotalNum = new HashMap<String, Integer>();
                while (tmpNowReadNum == 0 || tmpNowReadNum < tmpTotalNum.get("totalCount")) {
                    XmlTextWriter xmlTextWriter = new XmlTextWriter();
                    GXNX02Header header = new GXNX02Header();
                    //获取今日时间
                    Calendar todayFrom = Calendar.getInstance();
                    todayFrom.setTime(Format.Date8Format.parse(Format.Date8Format.format(new Date())));
                    int todayInt = Integer.parseInt(Format.Date8Format.format(todayFrom.getTime()));
                    //起始时间小于当前时间，查询历史。否则查询今日
                    if (Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime())) < todayInt) {
                        header.tranCode = "1004S";
                    } else {
                        header.tranCode = "1003S";
                    }
                    header.tranSeq = Format.DateTime14Format.format(new Date()) + bankFront.operator
                            + header.tranCode.substring(0, 4) + getQryTransID();
                    writeCommonHeader1(xmlTextWriter, header);
                    xmlTextWriter.writeStartElement("REQBODY");
//                    帐号	M	NString	34	AcctNo
                    xmlTextWriter.writeElementString("AcctNo", p_req7516.actNum);
                    //起始时间小于当前时间，查询历史。否则查询今日
                    if (Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime())) < todayInt) {
                        //起始日期	M	Date	10	BeginDate
                        xmlTextWriter.writeElementString("BeginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                        //终止日期	M	Date	10	EndDate
                        xmlTextWriter.writeElementString("EndDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                    }
                    //查询起始笔数
                    xmlTextWriter.writeElementString("BeginNo", tmpNowReadStart + "");
                    //默认为8笔
                    xmlTextWriter.writeElementString("QryNo", pagesize);
                    xmlTextWriter.writeEndDocument();
                    String[] bankResult = sendToBank1(xmlTextWriter.toXmlString());
                    if (bankResult[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1].trim(), tmpSbMsg);
                        if (tmpBkReader != null) {
                            String rspCode = tmpBkReader.getFirstText("/GXNXYQ/RESP/RESPHEAD/RspCode");
                            String rspMsg = tmpBkReader.getFirstText("/GXNXYQ/RESP/RESPHEAD/RspMsg");
                            if ("000000".equals(rspCode)) {
                                String tmpReadNum = tmpBkReader.getFirstText("/GXNXYQ/RESP/RESPBODY/MAININF/RetNo");
                                String totalCount = tmpBkReader.getFirstText("/GXNXYQ/RESP/RESPBODY/MAININF/SumNo");
                                if (StringHelper.hasAnyChar(tmpReadNum) && StringHelper.hasAnyChar(totalCount)) {
                                    if (tmpTotalNum.containsKey("totalCount")) {
                                        if (tmpTotalNum.get("totalCount").intValue() != Integer.valueOf(totalCount).intValue()) {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "相同条件前后查出来的总数不一致";
                                            break;
                                        }
                                    } else {
                                        if ("0".equals(totalCount)) {
                                            break;
                                        }
                                        tmpTotalNum.put("totalCount", Integer.valueOf(totalCount));
                                    }
                                    int readCount = 0;
                                    while (tmpBkReader.read("/GXNXYQ/RESP/RESPBODY/LIST/PARAM")) {
                                        XElement readXElement = tmpBkReader.readedXElement;
                                        RetAtsTransDetail detail = new RetAtsTransDetail();
                                        detail.actArea = p_req7516.actArea;
                                        detail.actNum = p_req7516.actNum;
                                        detail.tranDate = DateHelper.convertD8toD10(readXElement.getSingleTextNotNull("SndDate"));//交易日期
                                        detail.tranTime = detail.tranDate + " " + readXElement.getSingleTextNotNull("SndTime");//交易时间
                                        detail.valueDate = detail.tranDate;//起息日
                                        detail.recAccNum = readXElement.getSingleTextNotNull("RecAcctNo");//对方账号
                                        detail.recAccName = readXElement.getSingleTextNotNull("RecAcctName");//对方户名
                                        detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("TranCcy"));//币种
                                        detail.tranAmt = readXElement.getSingleTextNotNull("TranAmt");//交易金额
                                        detail.accBal = readXElement.getSingleTextNotNull("Bal");//交易后余额
                                        detail.usage = readXElement.getSingleTextNotNull("Useage");//用途
                                        detail.abstr = pickupAbstr(detail.usage);//对账码
                                        detail.askNumber = readXElement.getSingleTextNotNull("SerSeqNo");
                                        String cdFlag = readXElement.getSingleTextNotNull("CDFlag").trim();//借贷标志
                                        if (cdFlag.equals("C")) {
                                            if (detail.tranAmt.indexOf("-") >= 0) {
                                                detail.cdFlag = "1";
                                                detail.tranAmt = detail.tranAmt.substring(1);
                                            } else {
                                                detail.cdFlag = "2";
                                            }
                                        } else if (cdFlag.equals("D")) {
                                            if (detail.tranAmt.indexOf("-") >= 0) {
                                                detail.cdFlag = "2";
                                                detail.tranAmt = detail.tranAmt.substring(1);
                                            } else {
                                                detail.cdFlag = "1";
                                            }
                                        } else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "借贷标志( " + cdFlag + ")无法识别，请与银行核对";
                                            break;
                                        }
                                        retAtsTrans.writeRetDetail(detail);
                                        readCount++;
                                    }
                                    if ("-1".equals(tmpRespCode)) {
                                        break;
                                    }
                                    if (readCount != Integer.valueOf(tmpReadNum)) {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "统计明细有误";
                                        break;
                                    }
                                    tmpNowReadStart += readCount;
                                    tmpNowReadNum += readCount;
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "tmpReadNum=" + tmpReadNum + "&totalCount=" + totalCount;
                                    break;
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = rspMsg;
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = bankResult[1];
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("交易为空");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    /**
     * 今日明细查询
     *
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        return d_7515_TodayTransB(p_req7515);
    }

    public RetAtsTrans d_7515_TodayTransB(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
